// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = () => {
  let { OPENID } = cloud.getWXContext()
  const db = cloud.database() //获取数据库的引用
  let today = formatTime(new Date())
  db.collection('task').get().then(res => {
    let newData = res.data.map(item => {
      return {
        date: today,
        isFinish: false,
        name: item.name,
        _openid: item._openid
      }
    })
    db.collection('allUserTask').where({
      _openid: OPENID,
      date: today
    }).field({
      _openid: false
    }).get().then(res => {
      // 查重
      let data = newData.filter(item => {
        return res.data.findIndex(itemChild => item.name === itemChild.name) === -1
      })
      db.collection('allUserTask').add({ data }).then(res => {
        cloud.logger(res)
      }).catch(err => {
        cloud.logger(err)
      })
    })
  }).catch(err => {
    cloud.logger(err)
    reject(false)
  })
}

const formatTime = (date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return (
    [year, month, day].map(formatNumber).join('-')
  )
}

const formatNumber = (n) => {
  const s = n.toString()
  return s[1] ? s : '0' + s
}